#include "header.h"

extern struct SN_env * SN_create_env(int fc_S_size, int fc_I_size)
{
    struct SN_env * fc_z = (struct SN_env *) calloc(1, sizeof(struct SN_env));
    if (fc_z == NULL) return NULL;
    fc_z->p = create_s();
    if (fc_z->p == NULL) goto error;
    if (fc_S_size)
    {
        int fc_i;
        fc_z->S = (symbol * *) calloc(fc_S_size, sizeof(symbol *));
        if (fc_z->S == NULL) goto error;

        for (fc_i = 0; fc_i < fc_S_size; fc_i++)
        {
            fc_z->S[fc_i] = create_s();
            if (fc_z->S[fc_i] == NULL) goto error;
        }
    }

    if (fc_I_size)
    {
        fc_z->I = (int *) calloc(fc_I_size, sizeof(int));
        if (fc_z->I == NULL) goto error;
    }

    return fc_z;
error:
    SN_close_env(fc_z, fc_S_size);
    return NULL;
}

extern void SN_close_env(struct SN_env * fc_z, int fc_S_size)
{
    if (fc_z == NULL) return;
    if (fc_S_size)
    {
        int fc_i;
        for (fc_i = 0; fc_i < fc_S_size; fc_i++)
        {
            lose_s(fc_z->S[fc_i]);
        }
        free(fc_z->S);
    }
    free(fc_z->I);
    if (fc_z->p) lose_s(fc_z->p);
    free(fc_z);
}

extern int SN_set_current(struct SN_env * fc_z, int fc_size, const symbol * fc_s)
{
    int fc_err = replace_s(fc_z, 0, fc_z->l, fc_size, fc_s, NULL);
    fc_z->c = 0;
    return fc_err;
}
